#!/bin/env python3
#coding=utf-8
import pymysql


class dbcenter:
    def __init__(self, dbname):
        self.dbobj = pymysql.connect(
            "127.0.0.1",
            "root",
            "blldxt",
            dbname,
            use_unicode=True,
            charset="utf8"
        )
        self.cursor = self.dbobj.cursor()
        self.dictcursor = self.dbobj.cursor(
            pymysql.cursors.DictCursor
        )

    def select(self, select_list, where_obj, table, isone):
        swap = ",".join(select_list)
        where = '' if where_obj is None else " WHERE {0}".format(where_obj["text"])
        sql = "SELECT {0} FROM {1}{2}".format(swap, table, where)
        format_swap = tuple(where_obj["format"])
        if isone:
            self.cursor.execute(sql, format_swap)
            data = self.cursor.fetchone()
        else:
            self.dictcursor.execute(sql, where_obj["format"])
            data = self.listtojson(self.dictcursor.fetchall())
        # self.dbobj.close()
        return data

# insert
# insdict key : value dict
# table name
    def insert(self, insdict, table):
        dictkeys = insdict.keys()
        swap = ','.join(['%s' for x in dictkeys])
        formatvalues = tuple(insdict[x] for x in dictkeys)
        sql = "INSERT INTO {0} ({1}) VALUES ({2})".format(
            table,
            ','.join(dictkeys),
            swap
        )
        print(sql)
        try:
            self.cursor.execute(sql, formatvalues)
            self.dbobj.commit()
            # self.dbobj.close()
            return True
        except:
            self.dbobj.close()
            return False

    def listtojson(self, data) -> str:
        num = 0
        swap = {}
        for i in data:
            swap[str(num)] = i
            num += 1
        return swap
